import { defineStore } from 'pinia'
import type { Account } from '@/api/user/type'
import { login, userInfo, logout } from '@/api/user/index'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import router from '@/router'
import { constRoutes, asnycRoute, anyRoute } from '@/router/constRoutes'
import cloneDeep from 'lodash/cloneDeep'

//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    let urls = routes.map((v) => v.url)
    let idx = urls.indexOf(item.path)
    if (idx != -1) {
      if (item.children && item.children.length > 0) {
        //硅谷333账号:product\trademark\attr\sku
        item.children = filterAsyncRoute(item.children, routes[idx].children)
      }
      return true
    }
  })
}

// 你可以对 `defineStore()` 的返回值进行任意命名，但最好使用 store 的名字，同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`，`useCartStore`，`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useUserStore = defineStore('Users', {
  // 其他配置...
  state: () => ({
    token: GET_TOKEN(),
    menuRoutes: constRoutes,
    userId: '',
    nickName: '',
    avatar: '',
    birthday: '',
    description: '',
    hasUserInfo: false,
    auths: [],
    lang: localStorage.getItem('lang') || 'en'
  }),
  getters: {},
  actions: {
    // 登录
    async login(param: Account) {
      let { status, data, msg } = await login(param)

      if (status == 200) {
        let { token } = data
        this.token = token
        SET_TOKEN(token)
        return '登录成功'
      } else {
        return Promise.reject(new Error(msg))
      }
    },

    //获取用户信息方法
    async userInfo() {
      //获取用户信息进行存储仓库当中[用户头像、名字]
      const { data, msg, status } = await userInfo()

      //如果获取用户信息成功，存储一下用户信息
      if (status == 200) {
        const { auths, menus, userInfo } = data
        this.userId = userInfo.userId
        this.nickName = userInfo.nickName
        this.avatar = userInfo.avatar
        this.birthday = userInfo.birthday
        this.description = userInfo.description
        this.hasUserInfo = true
        this.auths = auths.map((v) => v.url)
        //计算当前用户需要展示的异步路由
        const userAsyncRoute = filterAsyncRoute(cloneDeep(asnycRoute), menus)
        // //菜单需要的数据整理完毕
        this.menuRoutes = [...constRoutes, ...userAsyncRoute, anyRoute]
        //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
        ;[...asnycRoute, anyRoute].forEach((route: any) => {
          router.addRoute(route)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(msg))
      }
    },
    async logout() {
      await logout()
      this.removeLoginCache()
    },
    removeLoginCache() {
      this.nickName = ''
      this.avatar = ''
      this.token = ''
      this.hasUserInfo = false
      REMOVE_TOKEN()
    },
  },
})
